package org.jeecg.common.util.oss;

import com.obs.services.ObsClient;
import com.obs.services.model.ObsObject;
import com.obs.services.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.filter.StrAttackFilter;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.Random;

@Slf4j
public class ObsBootUtil {

    private static String endPoint;
    private static String accessKeyId;
    private static String accessKeySecret;
    private static String bucketName;
    private static String staticDomain;

    public static void setEndPoint(String endPoint) {
        ObsBootUtil.endPoint = endPoint;
    }

    public static void setAccessKeyId(String accessKeyId) {
        ObsBootUtil.accessKeyId = accessKeyId;
    }

    public static void setAccessKeySecret(String accessKeySecret) {
        ObsBootUtil.accessKeySecret = accessKeySecret;
    }

    public static void setBucketName(String bucketName) {
        ObsBootUtil.bucketName = bucketName;
    }

    public static void setStaticDomain(String staticDomain) {
        ObsBootUtil.staticDomain = staticDomain;
    }

    public static String getStaticDomain() {
        return staticDomain;
    }

    public static String getEndPoint() {
        return endPoint;
    }

    public static String getAccessKeyId() {
        return accessKeyId;
    }

    public static String getAccessKeySecret() {
        return accessKeySecret;
    }

    public static String getBucketName() {
        return bucketName;
    }

    public static ObsClient getObsClient() {
        return obsClient;
    }

    /**
     * oss 工具客户端
     */
    private static volatile ObsClient obsClient = null;


    /**
     * 文件上传
     * @param file
     * @param fileDir
     * @return
     */
    public static String upload(MultipartFile file, String fileDir) {
        return upload(file, fileDir,null);
    }

    /**
     * 上传文件至华为云 OBS
     * 文件上传成功,返回文件完整访问路径
     * 文件上传失败,返回 null
     *
     * @param file    待上传文件
     * @param fileDir 文件保存目录
     * @return obs 中的相对文件路径
     */
    public static String upload(MultipartFile file, String fileDir, String customBucket){
        String FILE_URL = null;
        initOBS(endPoint, accessKeyId, accessKeySecret);
        StringBuilder fileUrl = new StringBuilder();
        String newBucket = bucketName;
        if(oConvertUtils.isNotEmpty(customBucket)){
            newBucket = customBucket;
        }
        try {
            //判断桶是否存在,不存在则创建桶
            if(!obsClient.headBucket(newBucket)){
                obsClient.createBucket(newBucket);
            }
            // 获取文件名
            String orgName = file.getOriginalFilename();
            if("".equals(orgName)){
                orgName=file.getName();
            }
            orgName = CommonUtils.getFileName(orgName);
            Random random = new Random();
            String fileName = System.currentTimeMillis() + "_" + random.nextInt(10000) + orgName.substring(orgName.lastIndexOf("."));
            if (!fileDir.endsWith("/")) {
                fileDir = fileDir.concat("/");
            }
            //update-begin-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符，防止攻击
            fileDir= StrAttackFilter.filter(fileDir);
            //update-end-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符，防止攻击
            fileUrl = fileUrl.append(fileDir + fileName);

            if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
                FILE_URL = staticDomain + "/" + fileUrl;
            } else {
                FILE_URL = "https://" + newBucket + "." + endPoint + "/" + fileUrl;
            }
            PutObjectResult result = obsClient.putObject(newBucket, fileUrl.toString(), file.getInputStream());
            if (result != null) {
                log.info("------OBS文件上传成功------" + fileUrl);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return FILE_URL;
    }


    /**
     * 初始化 obs 客户端
     *
     * @return
     */
    private static ObsClient initOBS(String endpoint, String accessKeyId, String accessKeySecret) {
        if (obsClient == null) {
            synchronized (ObsBootUtil.class) {
                if (obsClient == null) {
                    obsClient = new ObsClient(accessKeyId, accessKeySecret, endpoint);
                }
            }
        }
        return obsClient;
    }

    /**
     * 获取文件流
     * @param objectName
     * @return
     */
    public static InputStream getObsFile(String objectName){
        return getObsFile(objectName,null);
    }


    /**
     * 获取文件流
     * @param objectName
     * @param bucket
     * @return
     */
    public static InputStream getObsFile(String objectName, String bucket) {
        InputStream inputStream = null;
        try{
            String newBucket = bucketName;
            if(oConvertUtils.isNotEmpty(bucket)){
                newBucket = bucket;
            }
            initOBS(endPoint, accessKeyId, accessKeySecret);
            ObsObject object = obsClient.getObject(newBucket, objectName);
            inputStream = new BufferedInputStream(object.getObjectContent());
        }catch (Exception e){
            log.info("文件获取失败" + e.getMessage());
        }
        return inputStream;
    }

}
